<?php
// +----------------------------------------------------------------------
// | 菜单管理
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\common\controller\AdminBase;

/**
 * 后台菜单
 * Class Menu
 * @package app\admin\controller
 */
class Hsmenu extends AdminBase
{

    protected $auth_rule_model;

    protected function _initialize()
    {
        parent::_initialize();
        //$this->auth_rule_model = new AuthRuleModel();
        //$admin_menu_list       = $this->auth_rule_model->order(['sort' => 'DESC', 'id' => 'ASC'])->select();
        $admin_menu_list = db('auth_rule')->order(['sort' => 'DESC', 'id' => 'ASC'])->select();
        $admin_menu_level_list = array2level($admin_menu_list,'auth_rule');
        $this->assign('admin_menu_level_list', $admin_menu_level_list);
    }

    /**
     * 后台菜单
     * @return mixed
     */
    public function index()
    {
        return $this->fetch('index');
    }

    /**
     * 添加菜单
     * @param string $pid
     * @return mixed
     */
    public function add($pid = '')
    {
        return $this->fetch('add', ['pid' => $pid]);
    }

    /**
     * 保存菜单
     */
    public function save()
    {
        if (request()->isPost()) {
            $data            = input('post.');
            $data['id'] = (db('auth_rule')->max('id'))+1;
            if (db('auth_rule')->insert($data)) {
                $this->success('保存成功','index');
            } else {
                $this->error('保存失败');
            }
        }
    }

    /**
     * 编辑菜单
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        return $this->fetch('edit', ['admin_menu' => db('auth_rule')->find($id)]);
    }
    /**
     * 更新菜单状态
     * @param $id
     */
    public function setStatus($id){
        if (request()->isPost()) {
            $data = input('post.');
            if (db('auth_rule')->where(['id' => $id])->update($data) !== false) {
                $this->success('更新成功');
            } else {
                $this->error('更新失败');
            }
        }
    }
    /**
     * 更新菜单
     * @param $id
     */
    public function update($id){    //页面存在input name=id
        if (request()->isPost()) {
            $data            = input('post.');

            if (db('auth_rule')->update($data) !== false) {    //$data中存在主键
                $this->success('更新成功','index');
            } else {
                $this->error('更新失败');
            }
        }
    }

    /**
     * 删除菜单
     * @param $id
     */
    public function delete($id)
    {
        $sub_menu = db('auth_rule')->where(['pid' => $id])->find();
        if (!empty($sub_menu)) {
            $this->error('此菜单下存在子菜单，不可删除');
        }
        if (db('auth_rule')->delete($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}